/*
 * Copyright 2009 Knokode Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.knokode.osgi.osgihelp;

import java.io.File;
import java.io.IOException;

import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.codehaus.plexus.util.FileUtils;

/**
 * Maven mojo to resolve and copy artifacts (bundles) into 
 * a target folder
 *
 * @goal copy
 * @phase compile
 * 
 * @author Filippo Diotalevi
 */
public class CopyBundleMojo extends AbstractMojo
{
    /**
     * @component
     * @required
     * @readonly
     */
    private ArtifactFactory artifactFactory;

    /**
     * @parameter expression="${component.org.apache.maven.artifact.resolver.ArtifactResolver}"
     * @required
     * @readonly
     */
    protected org.apache.maven.artifact.resolver.ArtifactResolver resolver;

    /**
     * @parameter expression="${project.remoteArtifactRepositories}"
     * @readonly
     * @required
     */
    protected java.util.List remoteRepos;

    /**
     * @parameter expression="${localRepository}"
     * @readonly
     * @required
     */
    protected org.apache.maven.artifact.repository.ArtifactRepository local;

    /**
     * Target directory
     * @parameter 
     * @required
     */
    private File bundleDirectory;

    /**
     * Bundles to be copied
     * @parameter 
     */
    private String[] bundles;

    /**
     * Main method
     */
    public void execute() throws MojoExecutionException
    {
        if (bundleDirectory == null)
        {
            getLog().warn("You must specify a target directory to copy bundles");
            return;
        }

        getLog().info("Copying bundles into: " + bundleDirectory.getAbsolutePath());

        if (thereAre(bundles))
            resolveAndCopyArtifact();

    }

    private boolean thereAre(String[] contents)
    {
        return contents != null && contents.length > 0;
    }

    private void resolveAndCopyArtifact()
    {
        for (int i = 0; i < bundles.length; i++)
        {
            String[] tokens = bundles[i].split(":");
            if (tokens.length < 3)
            {
                getLog().warn(
                    "Bundle defined as " + bundles[i]
                        + " doesn't follow the naming convention and will be ignored");
                continue;
            }

            Artifact artifact = artifactFactory.createArtifact(tokens[0], tokens[1],
                tokens[2], "compile", "jar");

            try
            {
                resolver.resolve(artifact, remoteRepos, local);
                getLog().info(artifact.getFile() + "");
            }
            catch (ArtifactResolutionException e)
            {
                getLog().error("Cannot resolve " + bundles[i], e);
            }
            catch (ArtifactNotFoundException e)
            {
                getLog().error("Cannot find " + bundles[i], e);
            }

            try
            {
                FileUtils.copyFileToDirectory(artifact.getFile(), bundleDirectory);
            }
            catch (IOException e)
            {
                getLog().error(
                    "Cannot copy " + bundles[i] + " to directory "
                        + bundleDirectory.getAbsolutePath(), e);
            }
        }
    }
}
